<?php
// +----------------------------------------------------------------------
// | Bwsaas
// +----------------------------------------------------------------------
// | Copyright (c) 2015~2020 http://www.buwangyun.com All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Gitee ( https://gitee.com/buwangyun/bwsaas )
// +----------------------------------------------------------------------
// | Author: buwangyun <hnlg666@163.com>
// +----------------------------------------------------------------------
// | Date: 2020-9-28 10:55:00
// +----------------------------------------------------------------------

namespace buwang\util;

/**
 * RPC请求类
 */
class RpcClient
{
    public function send(string $serve, array $data = [], callable $callback = null)
    {

        //$raw = serialize($data);//注意序列化类型,需要和RPC服务端约定好协议 $serializeType
        try {
            $raw = json_encode($data, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);

            $fp = stream_socket_client($serve);
            fwrite($fp, pack('N', strlen($raw)) . $raw);//pack数据校验

            $data = fread($fp, 65533);
            //做长度头部校验
            $len = unpack('N', $data);
            $data = substr($data, '4');
            if (strlen($data) != $len[1]) {
                if (!is_null($callback)) {
                    call_user_func_array($callback, []);
                }
            } else {
                $data = json_decode($data, true);
                //    //这就是服务端返回的结果，
                //var_dump($data);//默认将返回一个response对象 通过$serializeType修改
                if (!is_null($callback)) {
                    call_user_func_array($callback, $data);
                }
            }
            fclose($fp);
        } catch (\think\exception\ErrorException $e) {
            echo $e->getMessage();
            echo '<hr/>';
        }

    }
}